//
//  BaseFlutterViewController.m
//  Project
//
//  Created by liting on 2025/9/1.
//

#import "BaseFlutterViewController.h"
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>
#import "RecommendVC.h"

static NSString *const kDefaultMethodChannelName = @"com.test.flutter/base_channel";
static NSString *const kParametersMethodChannelName = @"com.test.flutter/parameters_channel";

@interface BaseFlutterViewController () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) FlutterViewController *flutterViewController;
@property (nonatomic, strong) FlutterEngine *flutterEngine;
@property (nonatomic, assign) BOOL useIndependentEngine;
@property (nonatomic, strong) NSMutableDictionary<NSString *, FlutterMethodChannel *> *methodChannels;
@property (nonatomic, assign) BOOL isEngineAttached;

// 记录原始的导航栏隐藏状态
@property (nonatomic, assign) BOOL originalNavigationBarHidden;
// 记录是否已经处理过导航栏
@property (nonatomic, assign) BOOL hasHandledNavigationBar;

@property (nonatomic, strong) UIScreenEdgePanGestureRecognizer *popGestureRecognizer;

@end

@implementation BaseFlutterViewController

#pragma mark - 初始化方法（新增带参数的初始化方法）

+ (instancetype)controllerWithRoute:(nullable NSString *)route {
    return [[self alloc] initWithRoute:route useIndependentEngine:NO navigationBarHidden:NO parameters:nil];
}

+ (instancetype)controllerWithRoute:(nullable NSString *)route
                navigationBarHidden:(BOOL)hidden {
    return [[self alloc] initWithRoute:route useIndependentEngine:NO navigationBarHidden:hidden parameters:nil];
}

+ (instancetype)controllerWithRoute:(nullable NSString *)route
                         parameters:(nullable NSDictionary *)parameters {
    return [[self alloc] initWithRoute:route useIndependentEngine:NO navigationBarHidden:NO parameters:parameters];
}

+ (instancetype)controllerWithRoute:(nullable NSString *)route
                navigationBarHidden:(BOOL)hidden
               useIndependentEngine:(BOOL)independent
                         parameters:(nullable NSDictionary *)parameters {
    return [[self alloc] initWithRoute:route useIndependentEngine:independent navigationBarHidden:hidden parameters:parameters];
}

+ (instancetype)controllerWithIndependentEngineWithRoute:(nullable NSString *)route {
    return [[self alloc] initWithRoute:route useIndependentEngine:YES navigationBarHidden:NO parameters:nil];
}

+ (instancetype)controllerWithIndependentEngineWithRoute:(nullable NSString *)route
                                     navigationBarHidden:(BOOL)hidden {
    return [[self alloc] initWithRoute:route useIndependentEngine:YES navigationBarHidden:hidden parameters:nil];
}

+ (instancetype)controllerWithIndependentEngineWithRoute:(nullable NSString *)route
                                              parameters:(nullable NSDictionary *)parameters {
    return [[self alloc] initWithRoute:route useIndependentEngine:YES navigationBarHidden:NO parameters:parameters];
}

+ (instancetype)controllerWithIndependentEngineWithRoute:(nullable NSString *)route
                                     navigationBarHidden:(BOOL)hidden
                                              parameters:(nullable NSDictionary *)parameters {
    return [[self alloc] initWithRoute:route useIndependentEngine:YES navigationBarHidden:hidden parameters:parameters];
}

- (instancetype)initWithRoute:(nullable NSString *)route
         useIndependentEngine:(BOOL)independent
          navigationBarHidden:(BOOL)hidden
                   parameters:(nullable NSDictionary *)parameters {
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _initialRoute = route;
        _useIndependentEngine = independent;
        _isEngineAttached = NO;
        _navigationBarHidden = hidden;
        _autoRestoreNavigationBar = YES;
        _enableNavigationBarHandling = YES;
        _originalNavigationBarHidden = NO;
        _hasHandledNavigationBar = NO;
        _parameters = parameters;
    }
    return self;
}


#pragma mark - 视图生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupFlutterEngine];
    [self setupUI];
    [self registerDefaultMethodChannel];
    [self registerParametersChannel]; // 注册参数通道
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

#pragma mark - 方法通道

- (void)registerDefaultMethodChannel {
    FlutterMethodChannel *defaultChannel = [FlutterMethodChannel
                                            methodChannelWithName:kDefaultMethodChannelName
                                            binaryMessenger:self.flutterViewController.binaryMessenger];

    __weak typeof(self) weakSelf = self;
    [defaultChannel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
        [weakSelf handleMethodCall:call result:result];
    }];

    if (!self.methodChannels) {
        self.methodChannels = [NSMutableDictionary dictionary];
    }
    self.methodChannels[kDefaultMethodChannelName] = defaultChannel;
}


#pragma mark - 引擎管理和UI设置
- (void)setupFlutterEngine {
    if (self.useIndependentEngine) {
        [self setupIndependentEngine];
    } else {
        [self setupSmartSharedEngine];
    }
}

- (void)setupSmartSharedEngine {
    // 获取共享引擎
    FlutterEngine *sharedEngine = [self getSharedEngine];

    if (!sharedEngine) {
        NSLog(@"共享引擎未找到，使用独立引擎");
        [self setupIndependentEngine];
        return;
    }

    // 检查引擎是否被占用
    if (sharedEngine.viewController && sharedEngine.viewController != self.flutterViewController) {
        NSLog(@"共享引擎被占用，使用独立引擎");
        [self setupIndependentEngine];
        return;
    }

    _flutterEngine = sharedEngine;

    // 确保引擎运行
    if (![self isEngineReady]) {
        if (self.initialRoute) {
            [_flutterEngine runWithEntrypoint:nil initialRoute:self.initialRoute];
        } else {
            [_flutterEngine run];
        }
    }
}

// 新增：检查引擎是否就绪
- (BOOL)isEngineReady {
    // 通过检查二进制消息器来判断引擎是否就绪
    if (!_flutterEngine) {
        return NO;
    }else{
        return YES;
    }

    // 方法1：检查 binaryMessenger 是否可用
    //    if (!_flutterEngine.binaryMessenger) return NO;

    // 方法2：尝试发送一个简单的消息来检测引擎状态
    // 这里我们使用更简单的方式：检查 viewController 引用
    //    return _flutterEngine.viewController != nil;
}

// 新增：获取共享引擎
- (FlutterEngine *)getSharedEngine {
    id<UIApplicationDelegate> appDelegate = [UIApplication sharedApplication].delegate;
    if ([appDelegate respondsToSelector:@selector(flutterEngine)]) {
        return [appDelegate performSelector:@selector(flutterEngine)];
    }
    return nil;
}

// 修改清理方法
- (void)cleanup {
    // 移除所有通道处理器
    for (FlutterMethodChannel *channel in self.methodChannels.allValues) {
        [channel setMethodCallHandler:nil];
    }
    [self.methodChannels removeAllObjects];

    // 清理ViewController引用
    if (self.flutterEngine && self.flutterEngine.viewController == self.flutterViewController) {
        self.flutterEngine.viewController = nil;
    }

    // 彻底清理视图
    [self cleanupFlutterView];
}

// 新增：清理Flutter视图
- (void)cleanupFlutterView {
    if (self.flutterViewController) {
        [self.flutterViewController willMoveToParentViewController:nil];
        [self.flutterViewController.view removeFromSuperview];
        [self.flutterViewController removeFromParentViewController];
        self.flutterViewController = nil;
    }
}


- (void)setupSharedEngine {
    id<UIApplicationDelegate> appDelegate = [UIApplication sharedApplication].delegate;
    if ([appDelegate respondsToSelector:@selector(flutterEngine)]) {
        _flutterEngine = [appDelegate performSelector:@selector(flutterEngine)];

        // 重要：如果共享引擎已被占用，创建新的独立引擎
        if (_flutterEngine.viewController) {
            NSLog(@"共享引擎已被占用，创建新的独立引擎");
            [self setupIndependentEngine];
            return;
        }

        // 强制重新运行引擎以确保页面刷新
        [self restartFlutterEngineForNewPage];
    } else {
        NSLog(@"共享引擎未找到，创建新的独立引擎");
        [self setupIndependentEngine];
    }
}

- (void)restartFlutterEngineForNewPage {
    if (!self.flutterEngine) return;

    // 正确的引擎重启方式
    if (self.initialRoute) {
        // 使用新的初始路由重新运行引擎
        [self.flutterEngine runWithEntrypoint:nil initialRoute:self.initialRoute];
    } else {
        [self.flutterEngine run];
    }

    NSLog(@"共享引擎已重启，路由: %@", self.initialRoute ?: @"默认路由");
}


- (void)setupIndependentEngine {
    NSString *engineName = [NSString stringWithFormat:@"independent_engine_%f", [[NSDate date] timeIntervalSince1970]];
    _flutterEngine = [[FlutterEngine alloc] initWithName:engineName];

    if (_initialRoute) {
        [_flutterEngine runWithEntrypoint:nil initialRoute:_initialRoute];
    } else {
        [_flutterEngine run];
    }

    [GeneratedPluginRegistrant registerWithRegistry:_flutterEngine];
    _useIndependentEngine = YES;
}



- (void)setupUI {
    self.flutterViewController = [[FlutterViewController alloc] initWithEngine:self.flutterEngine nibName:nil bundle:nil];
    self.isEngineAttached = YES;

    [self addChildViewController:self.flutterViewController];
    self.flutterViewController.view.frame = self.view.bounds;
    self.flutterViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.flutterViewController.view];
    [self.flutterViewController didMoveToParentViewController:self];

    // 设置背景色
    self.view.backgroundColor = [UIColor whiteColor];
    self.flutterViewController.view.backgroundColor = [UIColor whiteColor];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // 记录原始状态（只在第一次时记录）
    if (!self.hasHandledNavigationBar && self.navigationController) {
        self.originalNavigationBarHidden = self.navigationController.navigationBarHidden;
        self.hasHandledNavigationBar = YES;
    }

    // 设置导航栏状态
    if (self.enableNavigationBarHandling && self.navigationController) {
        [self.navigationController setNavigationBarHidden:self.navigationBarHidden animated:animated];
    }
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    // 恢复原始导航栏状态
    if (self.autoRestoreNavigationBar && self.hasHandledNavigationBar && self.navigationController) {
        [self.navigationController setNavigationBarHidden:self.originalNavigationBarHidden animated:animated];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // 发送参数到Flutter页面
    if (self.parameters) {
        [self sendParametersToFlutter:self.parameters];
    }

    [self callFlutterMethod:@"onPageDidAppear" arguments:nil completion:nil];
}

#pragma mark - 参数传递相关方法

/// 注册参数传递专用通道
- (void)registerParametersChannel {
    FlutterMethodChannel *parametersChannel = [FlutterMethodChannel
                                               methodChannelWithName:kParametersMethodChannelName
                                               binaryMessenger:self.flutterViewController.binaryMessenger];

    __weak typeof(self) weakSelf = self;
    [parametersChannel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
        [weakSelf handleParametersMethodCall:call result:result];
    }];

    if (!self.methodChannels) {
        self.methodChannels = [NSMutableDictionary dictionary];
    }
    self.methodChannels[kParametersMethodChannelName] = parametersChannel;
}

/// 发送参数到Flutter页面
- (void)sendParametersToFlutter:(NSDictionary *)parameters {
    if (!parameters || parameters.count == 0) return;

    [self.methodChannels[kParametersMethodChannelName] invokeMethod:@"receiveParameters" arguments:parameters];
}

/// 处理参数相关的方法调用
- (void)handleParametersMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([@"getInitialParameters" isEqualToString:call.method]) {
        // Flutter端请求初始参数
        result(self.parameters ?: @{});
    }
    else if ([@"getNativeParameters" isEqualToString:call.method]) {
        // 通过默认通道获取参数
        result(self.parameters ?: @{});
    }
    else if ([@"receiveParameters" isEqualToString:call.method]) {
        // 接收来自Flutter的参数（如果需要双向通信）
        if (call.arguments && [call.arguments isKindOfClass:[NSDictionary class]]) {
            NSLog(@"Received parameters from Flutter: %@", call.arguments);
        }
        result(@(YES));
    }
    else {
        result(FlutterMethodNotImplemented);
    }
}

#pragma mark - 默认方法处理（修改）

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([@"getPlatformVersion" isEqualToString:call.method]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }
    else if ([@"popPage" isEqualToString:call.method]) {
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        } else if (self.presentingViewController) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        result(@(YES));
    }
    else if ([@"dismissPage" isEqualToString:call.method]) {
        if (self.presentingViewController) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        result(@(YES));
    }
    else if ([@"showNavigationBar" isEqualToString:call.method]) {
        [self safeShowNavigationBarAnimated:YES];
        result(@(YES));
    }
    else if ([@"hideNavigationBar" isEqualToString:call.method]) {
        [self safeHideNavigationBarAnimated:YES];
        result(@(YES));
    }
    else if ([@"getNativeParameters" isEqualToString:call.method]) {
        // 通过默认通道获取参数
        result(self.parameters ?: @{});
    }
    else if ([@"pushRecommendPage" isEqualToString:call.method]) {
        RecommendVC *view = [[RecommendVC alloc]init];
        view.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:view animated:YES];
    }else {
        result(FlutterMethodNotImplemented);
    }
}

- (void)registerMethodChannelWithName:(nonnull NSString *)channelName handler:(nonnull FlutterMethodCallHandler)handler {
}

#pragma mark - 安全的导航栏控制方法

- (void)safeShowNavigationBarAnimated:(BOOL)animated {
    self.navigationBarHidden = NO;
    if (self.navigationController) {
        [self.navigationController setNavigationBarHidden:NO animated:animated];
    }
}

- (void)safeHideNavigationBarAnimated:(BOOL)animated {
    self.navigationBarHidden = YES;
    if (self.navigationController) {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }
}

- (void)safeToggleNavigationBarAnimated:(BOOL)animated {
    self.navigationBarHidden = !self.navigationBarHidden;
    if (self.navigationController) {
        [self.navigationController setNavigationBarHidden:self.navigationBarHidden animated:animated];
    }
}
- (void)callFlutterMethod:(NSString *)method
                arguments:(nullable id)arguments
               completion:(nullable FlutterResult)completion {
    if (!method || method.length == 0) {
        if (completion) {
            completion([FlutterError errorWithCode:@"INVALID_METHOD" message:@"Method name cannot be empty" details:nil]);
        }
        return;
    }

    [self.methodChannel invokeMethod:method arguments:arguments result:completion];
}

- (void)releaseResources {
    [self cleanup];
    
    if (self.useIndependentEngine && self.flutterEngine) {
        [self.flutterEngine destroyContext];
        self.flutterEngine = nil;
        NSLog(@"独立Flutter引擎已释放");
    }
}


-(void)dealloc {
    [self releaseResources];
    NSLog(@"%@ dealloc", NSStringFromClass([self class]));
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"收到内存警告，释放Flutter资源");
    [self releaseResources];
}

@end
